package com.example.app;

import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.fragment.NavHostFragment;
import androidx.navigation.ui.NavigationUI;

import com.example.app.ui.connect.ConnectFragment;
import com.example.app.ui.settings.SettingsFragment;
import com.google.android.material.bottomnavigation.BottomNavigationView;

import java.util.UUID;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private TextView connectionStatus;
    private TextView versionInfo;
    private TextView batteryLevel;
    private ImageView batteryIcon;
    private TextView dpiValue;
    private Button btnDisconnect;
    private Button btnUpdate;
    private NavController navController;
    private BluetoothGatt bluetoothGatt;
    private BluetoothGattCharacteristic writeCharacteristic;
    private static final UUID SERVICE_UUID = UUID.fromString("C1D02500-2D20-400A-95D2-6A2F7BCA0C25");
    private static final UUID WRITE_CHAR_UUID = UUID.fromString("C1D02505-2D20-400A-95D2-6A2F7BCA0C25");
    private int currentDpi = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 初始化UI元素
        connectionStatus = findViewById(R.id.connection_status);
        versionInfo = findViewById(R.id.version_info);
        batteryLevel = findViewById(R.id.battery_level);
        batteryIcon = findViewById(R.id.battery_icon);
        dpiValue = findViewById(R.id.dpi_value);
        btnDisconnect = findViewById(R.id.btn_disconnect);
        btnUpdate = findViewById(R.id.btn_update);

        // 设置断开连接按钮点击事件
        btnDisconnect.setOnClickListener(v -> {
            if (bluetoothGatt != null) {
                bluetoothGatt.disconnect();
            }
        });

        // 设置升级按钮点击事件
        btnUpdate.setOnClickListener(v -> {
            if (isDeviceConnected()) {
                // TODO: 实现升级功能

                Toast.makeText(this, "开始检查固件版本", Toast.LENGTH_SHORT).show();
                Fragment navHostFragment = getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment);
                if (navHostFragment != null) {
                    Fragment currentFragment = navHostFragment.getChildFragmentManager().getPrimaryNavigationFragment();
                    if (currentFragment instanceof ConnectFragment) {
                        ((ConnectFragment) currentFragment).startOtaUpgrade();
                    }
                }
            } else {
                Toast.makeText(this, "设备未连接", Toast.LENGTH_SHORT).show();
            }
        });

        // 初始化底部导航
        BottomNavigationView bottomNav = findViewById(R.id.nav_view);
        NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment);
        if (navHostFragment != null) {
            navController = navHostFragment.getNavController();
            NavigationUI.setupWithNavController(bottomNav, navController);
            // 增加如下监听，确保切换
            bottomNav.setOnItemSelectedListener(item -> {
                if (navController != null) {
                    int itemId = item.getItemId();
                    if (itemId == R.id.navigation_connect) {
                        navController.navigate(R.id.navigation_connect);
                        return true;
                    } else if (itemId == R.id.navigation_chat) {
                        navController.navigate(R.id.navigation_chat);
                        return true;
                    } else if (itemId == R.id.navigation_settings) {
                        navController.navigate(R.id.navigation_settings);
                        return true;
                    }
                }
                return false;
            });
        }
    }

    // 更新设备信息UI
    private void updateDeviceInfo(int hwVerNum, int fwVerNum, int batteryLevel, int dpiValue) {
        runOnUiThread(() -> {
            // 更新版本信息
            String versionText = String.format("版本: %d.%d", hwVerNum, fwVerNum);
            versionInfo.setText(versionText);

            // 更新电量信息
            String batteryText = String.format("%d%%", batteryLevel);
            this.batteryLevel.setText(batteryText);
            updateBatteryIcon(batteryLevel);

            // 更新DPI信息
            String dpiText = String.format("DPI: %d", dpiValue);
            this.dpiValue.setText(dpiText);
        });
    }

    // 更新电池图标
    private void updateBatteryIcon(int batteryLevel) {
        int iconResId;
        if (batteryLevel >= 90) {
            iconResId = R.drawable.ic_battery_full;
        } else if (batteryLevel >= 60) {
            iconResId = R.drawable.ic_battery_high;
        } else if (batteryLevel >= 30) {
            iconResId = R.drawable.ic_battery_medium;
        } else if (batteryLevel >= 10) {
            iconResId = R.drawable.ic_battery_low;
        } else {
            iconResId = R.drawable.ic_battery_empty;
        }
        batteryIcon.setImageResource(iconResId);
    }

    // 更新连接状态
    private void updateConnectionStatus(boolean isConnected, String deviceName) {
        runOnUiThread(() -> {
            if (isConnected) {
                connectionStatus.setText(String.format("已连接: %s", deviceName));
                btnDisconnect.setVisibility(View.VISIBLE);
                btnUpdate.setVisibility(View.VISIBLE);
            } else {
                connectionStatus.setText("连接状态：未连接");
                btnDisconnect.setVisibility(View.GONE);
                btnUpdate.setVisibility(View.GONE);
                // 重置其他信息
                versionInfo.setText("版本: --");
                batteryLevel.setText("--%");
                dpiValue.setText("DPI: --");
                batteryIcon.setImageResource(R.drawable.ic_battery_unknown);
            }
        });
    }

    // 获取当前DPI值
    public int getCurrentDpi() {
        return currentDpi;
    }

    // 获取版本信息
    public String getVersionInfo() {
        return versionInfo.getText().toString();
    }

    // 在收到设备信息时调用此方法
    public void onDeviceInfoReceived(int hwVerNum, int fwVerNum, int batteryLevel, int dpiValue) {
        currentDpi = dpiValue;
        updateDeviceInfo(hwVerNum, fwVerNum, batteryLevel, dpiValue);
    }

    // 在连接状态改变时调用此方法
    public void onConnectionStateChanged(boolean isConnected, String deviceName) {
        Log.d(TAG, "连接状态改变: " + (isConnected ? "已连接" : "未连接") + ", 设备名称: " + deviceName);
        updateConnectionStatus(isConnected, deviceName);
        if (!isConnected) {
            bluetoothGatt = null;
            writeCharacteristic = null;
            Log.d(TAG, "连接断开，重置bluetoothGatt和writeCharacteristic");
        }
    }

    public void navigateToChat() {
        if (navController != null) {
            navController.navigate(R.id.navigation_chat);
        }
    }

    public boolean isDeviceConnected() {
        boolean connected = bluetoothGatt != null && writeCharacteristic != null;
        Log.d(TAG, "检查设备连接状态: " + (connected ? "已连接" : "未连接") + 
              ", bluetoothGatt: " + (bluetoothGatt != null ? "非空" : "空") + 
              ", writeCharacteristic: " + (writeCharacteristic != null ? "非空" : "空"));
        return connected;
    }

    public void sendCommand(byte cmd, byte[] data) {
        Log.d(TAG, "尝试发送命令，连接状态: " + (isDeviceConnected() ? "已连接" : "未连接"));
        if (isDeviceConnected()) {
            // 构造完整命令
            byte[] command = new byte[data.length + 3];  // cmd(1) + crc16(2) + data
            command[0] = cmd;
            System.arraycopy(data, 0, command, 3, data.length);

            // 计算CRC16（只计算数据域，不包含cmd和crc16）
            short crc16 = calculateCRC16(3, command);
            command[1] = (byte) (crc16 & 0xFF);
            command[2] = (byte) ((crc16 >> 8) & 0xFF);

            // 打印发送的指令内容，用于调试
            StringBuilder sb = new StringBuilder();
            for (byte b : command) {
                sb.append(String.format("%02X ", b));
            }
            Log.i(TAG, "准备发送指令: " + sb.toString());
            Log.i(TAG, "命令类型: 0x" + String.format("%02X", cmd));
            Log.i(TAG, "CRC16: 0x" + String.format("%04X", crc16));
            Log.i(TAG, "数据长度: " + data.length);

            writeCharacteristic.setValue(command);
            boolean success = bluetoothGatt.writeCharacteristic(writeCharacteristic);
            Log.d(TAG, "命令发送" + (success ? "成功" : "失败"));
            if (!success) {
                Toast.makeText(this, "命令发送失败", Toast.LENGTH_SHORT).show();
            }
        } else {
            Log.e(TAG, "设备未连接，无法发送命令");
            Toast.makeText(this, "设备未连接", Toast.LENGTH_SHORT).show();
        }
    }

    // 添加CRC16计算方法
    private short calculateCRC16(int offset, byte[] data) {
        int genpoly = 0xA001;
        int ret = 0xFFFF;
        for (int i = offset; i < data.length; i++) {
            ret = (ret & 0xFFFF) ^ (data[i] & 0xFF);
            for (int index = 0; index < 8; index++) {
                if ((ret & 0x0001) == 1) {
                    ret = (ret >> 1) ^ genpoly;
                } else {
                    ret = ret >> 1;
                }
            }
        }
        return (short) (ret & 0xFFFF);
    }

    // 添加设置bluetoothGatt的方法
    public void setBluetoothGatt(BluetoothGatt gatt) {
        Log.d(TAG, "设置bluetoothGatt: " + (gatt != null ? "非空" : "空"));
        this.bluetoothGatt = gatt;
    }


    // 添加初始化writeCharacteristic的方法
    public void initializeWriteCharacteristic() {
        Log.d(TAG, "初始化writeCharacteristic");
        if (bluetoothGatt != null) {
            BluetoothGattService service = bluetoothGatt.getService(SERVICE_UUID);
            if (service != null) {
                writeCharacteristic = service.getCharacteristic(WRITE_CHAR_UUID);
                Log.d(TAG, "writeCharacteristic初始化: " + (writeCharacteristic != null ? "成功" : "失败"));
            } else {
                Log.e(TAG, "未找到服务: " + SERVICE_UUID);
            }
        }
    }

    public void disconnectDevice() {
        if (bluetoothGatt != null) {
            bluetoothGatt.disconnect();
            bluetoothGatt.close();
            bluetoothGatt = null;
            writeCharacteristic = null;
            
            // 更新UI状态
            onConnectionStateChanged(false, null);
        }
    }

} 